
/*
 * I don't know the correct name for this sequence.  it is a musical sequence
 * similar to the "middle c" sequence, but it is based on the pell numbers
 * or "silver ratio" (1 + sqrt 2)  rather than the fibonacci series or "golden
 * ratio" ((1 + sqrt 5) / 2) as the "middle c" sequence is
 *
 * here are the definitions of the silver and golden ratios:
 *
 * silver ratio: (2a + b) / a == a / b
 * golden ratio: (a + b) / a == a / b
 *
 */

var middle_d_sqrt2 = Math.sqrt(2);
var middle_d_half_ds = (1 + middle_d_sqrt2) / 2;
var middle_d_data;

function middle_d_expand_sequence() {

	var np = middle_d_data.m.length;
	var o = middle_d_data.m;
	var a = middle_d_data.a;
	var b = middle_d_data.b;
	var na = []; na = na.concat(a, b);
	var nb = []; nb = nb.concat(a, a, b);
	o = o.concat(na, nb);
	middle_d_data.a = na;
	middle_d_data.b = nb;
	middle_d_data.m = o;
	for (var i = np; i < middle_d_data.m.length; ++i) {
		middle_d_data.S[i] = middle_d_data.S[i - 1];
		middle_d_data.L[i] = middle_d_data.L[i - 1];
		++middle_d_data[middle_d_data.m[i]][i];
	}
}

function middle_d_get_gaps(t) {
	if (0 == t) { return ['S', 'L']; }
	var m = ((t < 0) ? -1 : 1);
	if (1 == t) { return ['L', 'S']; }
	if (-1 == t) { return ['S', 'S']; }
	var i = Math.abs(t) - 2;
	return ([middle_d_get_term(i), middle_d_get_term(i + 1)]);
}

function middle_d_get_distance(t) {
	if (0 == t) { return - middle_d_half_ds + 1; }
	// if this is term 0, return the center;
	var m = ((t < 0) ? -1 : 1);
	var i = Math.abs(t) - 2;
	middle_d_get_term(i + 5);
	var d = middle_d_half_ds * m;
	if (i < 0) { return d; }
	d += m * (middle_d_data.S[i] + middle_d_data.L[i] * middle_d_sqrt2);
	return d;
}

function middle_d_get_term(n) {
	var t = Math.abs(n);
	if (null == middle_d_data) { middle_d_data = {
		m: ['S', 'L'],
		a: ['S'],
		b: ['L'],
		S: [1, 1], // accumulate a count of shorts
		L: [0, 1], // accumulate a count of longs
		p: 1
	}}
	while (middle_d_data.m.length < t) {
		middle_d_expand_sequence();
	}
	return middle_d_data.m[t];
}

